package com.zlf.servlet;

import org.apache.catalina.CometEvent;
import org.apache.catalina.CometProcessor;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * Created by Administrator on 2016/12/25.
 *
 * @author zlf
 */
public class CometProcessorServlet extends HttpServlet implements CometProcessor {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        System.out.println("----------------post");
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        PrintWriter out = response.getWriter();

        // 由于浏览器原因（FireFox、IE有这个问题，Chrome正常），接收到的数据不会立即输出到页面上。这里首先输入长度大于1024的字符串。
        StringBuilder sb = new StringBuilder();
        for(int i = 0; i < 1024; i++) {
            sb.append('a');
        }
        out.println("<!-- " + sb.toString() + " -->"); // 注意加上HTML注释
        out.flush();

        while(true) {

            // 这里用Thread.sleep来模拟comet，相当于每隔5秒服务器向客户端推送一条消息
            try {
                Thread.sleep(5000);
                System.out.println("----------------get");
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

            // 每隔5秒写一段js到iframe中，去调用parent的addMsg函数，向HTML添加内容
            out.println("<div>parent.addMsg('helloworld<br>')</div>");
            out.flush(); // 这里一定要flush，否则数据不发送
        }

    }

    private static final long serialVersionUID = 1L;
    private static final Integer TIMEOUT = 10 * 1000;

    private MessageSender sender = null;

    public void event(CometEvent event) throws IOException, ServletException {

        HttpServletRequest request = event.getHttpServletRequest();
        HttpServletResponse response = event.getHttpServletResponse();

        if (event.getEventType() == CometEvent.EventType.BEGIN) {
            log("Begin for session: " + request.getSession(true).getId());
            request.setAttribute("org.apache.tomcat.comet.timeout", TIMEOUT);

            sender = new MessageSender(response);
            sender.start();

        } else if (event.getEventType() == CometEvent.EventType.ERROR) {
            log("Error for session: " + request.getSession(true).getId());
            event.close();
        } else if (event.getEventType() == CometEvent.EventType.END) {
            log("End for session: " + request.getSession(true).getId());
            event.close();
        } else if (event.getEventType() == CometEvent.EventType.READ) {
            throw new UnsupportedOperationException("This servlet does not accept data");
        }
        System.out.println("----------------event");
    }

    @Override
    public void destroy() {
        System.out.println("----------------destroy");
        sender.interrupt();
        sender = null;
    }
}
